package com.dragonlance.dao;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.dragonlance.beans.User;

public class UserDao extends BaseDao {
	public User findByUserName(String userName){
		ResultSetHandler<User> rsh = new BeanHandler<User>(User.class);
		User result = null;
		try {
			result = qryRun.query(conn,"select * from " + User.class.getSimpleName() + " where UserName=?", rsh, new Object[] { userName });
			logger.debug("SQL: select * from " + User.class.getSimpleName() + " where UserName=" + userName);
		} catch (SQLException e) {
			logger.error("Can not this query table " + User.class.getSimpleName(), e);
		}
		return result;
	}
	
	@Override
	public <User> void save(User user){
		String sql = "update user set nickName=?," +
				"level=?," +
				"exp=?," +
				"avatar=?," +
				"totalMp=?," +
				"totalHp=?," +
				"actions=?," +
				"attack=?," +
				"defence=?," +
				"strength=?," +
				"agility=?," +
				"intelligence=?," +
				"hit=?," +
				"dodge=?," +
				"crit=?," +
				"walkSpeed=?," +
				"money=?," +
				"loginTime=?" +
				" where uid=?";  
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
	        String[] propertyName = {"nickName",
	        		"level",
	        		"exp",
	        		"avatar",
	        		"totalMp",
	        		"totalHp",
	        		"actions",
	        		"attack",
	        		"defence",
	        		"strength",
	        		"agility",
    				"intelligence",
    				"hit",
    				"dodge",
    				"crit",
    				"walkSpeed",
    				"money",
    				"loginTime",
	        		"uid"};
	        qryRun.fillStatementWithBean(ps, user, propertyName);  
	        ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void fill() throws SQLException {
		User user = new User();
		user.setUserName("user0");
		user.setNickName("nickname0");
	    PreparedStatement ps = conn.prepareStatement(
	        "insert into user (username, password) values (?, ?)");
	    qryRun.fillStatementWithBean(ps, user, "userName", "password");
	    ps.executeUpdate();
	  }
}
